#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-06-07 15:08:38
# @Author  : rwecho rwecho@126.com
# @Description    : 

import requests
import json
import os


def download_bing_image(day):
    """
    download the bing background image for current day.
    :param day: defines the day of the picture:0 = today, 1 = yesterday, ....20
    :return: None
    """
    resultFormat = 'js'  # xml,js,rss
    bing_paper_url = 'http://www.bing.com/HPImageArchive.aspx?format=%s&idx=%d&n=1&mkt=en-US' % (resultFormat, day)
    bing_paper_content = requests.get(bing_paper_url)
    bing_paper_json = json.loads(bing_paper_content.text)

    if len(bing_paper_json['images']) == 0:
        print('there is no images')
    else:
        bing_image = bing_paper_json['images'][0]
        # bing_image_copyright = bing_image['copyright']
        bing_image_url = bing_image['url']
        # bing_image_msg = bing_image['msg']

        onedrivepath = 'C:\\Users\\rwgl517\\OneDrive\\图片\\wallpaper\\'
        filename = onedrivepath + os.path.basename(bing_image_url)
        print(filename)
        response = requests.get(bing_image_url, stream=True)
        if response.status_code == 200:
            with open(filename, 'wb') as out_file:
                for chunk in response.iter_content(1024):
                    out_file.write(chunk)
        del response
        print('download success')


if __name__ == '__main__':
    idx = 0
    download_bing_image(idx)

